//
//  GPSHelper.m
//  BosidengIphone
//
//  Created by  on 12-1-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "GPSHelper.h"

@implementation GPSHelper
@synthesize delegate;

- (id)init {
    if (self = [super init]) {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//精度要求最高级，导航级别
        locationManager.distanceFilter = 5;//距离过滤5m
        locationManager.delegate = self;
    }
    return self;
}

- (void)dealloc {
    self.delegate = nil;
    [locationManager release];
    [super dealloc];
}

- (void)locationManager:(CLLocationManager *)manager
	   didFailWithError:(NSError *)error {
	NSLog(@"locationManager start error %@", error);
    [self stopHeading];
    [self stopLocation];
}

- (void)locationManager:(CLLocationManager *)manager 
	   didUpdataHeading:(CLHeading *)newHeading {
	NSLog(@"Heading Updated newHeading is %@", newHeading);
    if (delegate) {
        [delegate updataHeading:newHeading.trueHeading];
    }
}

//GPS位置更新的回调
- (void)locationManager:(CLLocationManager *)manager 
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation {
    
	CLLocationCoordinate2D coordinate = newLocation.coordinate;
	double accuracy = newLocation.horizontalAccuracy;
	NSLog(@"纬度 %f˚ 经度 %f˚ 误差 %.0fm", coordinate.latitude, coordinate.longitude, accuracy);
	//if (accuracy > MIN_ACCURACY) {
	//	return;
	//}
	if (delegate) {
        [delegate updataLocation:coordinate];
    }
	//CLLocation *locationCoordinate = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    //distance = (NSInteger)[locationCoordinate distanceFromLocation:tagCoordinate];
    //NSLog(@"id(%@) distance=%d", tag.tagId, distance);
}

//开启电子罗盘
- (void)startHeading {
	if ([CLLocationManager headingAvailable]) {
		[locationManager startUpdatingHeading];
	}
}

//关闭电子罗盘
- (void)stopHeading {
	[locationManager stopUpdatingHeading];
}

//开启GPS
- (void)startLocation {
	if([CLLocationManager locationServicesEnabled]) {
		[locationManager startUpdatingLocation];
	}
}

//关闭GPS
- (void)stopLocation {
	[locationManager stopUpdatingLocation];
}

@end
